package de.tudarmstadt.ukp.muip.fibqdojo.io.raw;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartElement;

import com.google.common.base.Optional;

import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQToken;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.AbstractGetPiecesVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.GetDanPiecesVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.GetFormPiecesVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.GetKanaPiecesVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.GetKeiPiecesVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.GetLemmaPiecesVisitor;
import de.tudarmstadt.ukp.muip.fibqdojo.japanese.visitor.GetPosPiecesVisitor;

public class JapaneseTokenWriter extends AbstractTokenWriter implements RawIOJapanese_Constants {

    public JapaneseTokenWriter(XMLEventFactory eventFactory, XMLEventWriter eventWriter) {
        super(eventFactory, eventWriter);
    }

    public void processToken(IFIBQToken token) throws XMLStreamException {

        addNode(token, FORM, new GetFormPiecesVisitor());
        addNode(token, POS, new GetPosPiecesVisitor());
        addNode(token, LEMMA, new GetLemmaPiecesVisitor());
        addNode(token, KANA, new GetKanaPiecesVisitor());
        addNode(token, KEI, new GetKeiPiecesVisitor());
        addNode(token, DAN, new GetDanPiecesVisitor());

    }

    private void addNode(IFIBQToken token, String name, AbstractGetPiecesVisitor piecesVisitor)
            throws XMLStreamException {
        token.accept(piecesVisitor);
        Optional<String[]> pieces = piecesVisitor.getPieces();
        if (pieces.isPresent()) {
            StartElement sentStartElement = eventFactory.createStartElement("", "", name);
            eventWriter.add(sentStartElement);
            for (String piece : pieces.get()) {
                // open pice
                StartElement pieceStart = eventFactory.createStartElement("", "", PIECE);
                eventWriter.add(pieceStart);
                // write value
                Characters characters = eventFactory.createCharacters(piece);
                eventWriter.add(characters);
                // close piece
                eventWriter.add(eventFactory.createEndElement("", "", name));
            }
            eventWriter.add(eventFactory.createEndElement("", "", name));
        }

    }

}
